package com.channel.connector.ctripos.common.util;

import com.thoughtworks.xstream.XStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.OutputStream;
import java.io.Writer;

/**
 * 添加xml头的解析器
 * @author zhaoshan
 *
 */
public class XmlDeclarationXStream extends XStream {
	private static Log log = LogFactory.getLog(XmlDeclarationXStream.class);
	private String version;

	private String ecoding;
	private String standalone;
	public XmlDeclarationXStream() {
		this("1.0", "UTF-8", "yes");
	}

	public XmlDeclarationXStream(String version, String ecoding, String standalone) {
		this.version = version;
		this.ecoding = ecoding;
		this.standalone = standalone;
	}

	public String getDeclaration() {
		return "<?xml version=\"" + this.version + "\" encoding=\""
				+ this.ecoding + "\" standalone=\"" + this.standalone + "\"?>\r\n";
	}

	@Override
	public void toXML(Object arg0, OutputStream arg1) {
		try {
			String dec = this.getDeclaration();
			byte[] bytesOfDec = dec.getBytes(this.ecoding);
			arg1.write(bytesOfDec);
		} catch (Exception e) {
			log.error("输出Declaration时候出现异常", e);
			return;
		}
		super.toXML(arg0, arg1);
	}

	@Override
	public void toXML(Object arg0, Writer arg1) {
		try {
			arg1.write(getDeclaration());
		} catch (Exception e) {
			log.error("输出Declaration时候出现异常", e);
			return;
		}
		super.toXML(arg0, arg1);
	}
}
